/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.helper;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.smart.common.utils.AssertUtil;
import com.smart.context.SessionContext;
import com.smart.mapper.JiansheProjectMapper;
import com.smart.mapper.ProjectReportMapper;
import com.smart.mapper.ProjectTempTaskMapper;
import com.smart.model.convert.ProjectConvert;
import com.smart.model.domain.ProjectDO;
import com.smart.model.domain.ProjectTempTaskDO;
import com.smart.model.request.ProjectReportStatisticsRequest;
import com.smart.model.vo.ProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author zhanghong
 * @version TempHelper.java, v 0.1 2023/7/20 00:38 下午 TempHelper Exp $$
 */
@Slf4j
@Component
public class TempHelper {
    @Autowired
    private ProjectTempTaskMapper projectTempTaskMapper;
    @Autowired
    private ProjectReportMapper projectReportMapper;
    @Autowired
    private JiansheProjectMapper jiansheProjectMapper;

    public Pair<String, List<ProjectVO>> queryExportData(ProjectReportStatisticsRequest request) {
        // 前置校验
        ProjectTempTaskDO taskDO = projectTempTaskMapper.selectDOById(request.getId());
        AssertUtil.assertNotNull(taskDO, "临时提报任务不存在");

        request.setTaskId(taskDO.getId());
        // 建设单位只能看到当前所关联项目的提报数据
        if (SessionContext.getJiansheUnitId() != null) {
            List<Long> relationProjectList = jiansheProjectMapper.selectAllProjectId(SessionContext.getJiansheUnitId());
            if (CollectionUtils.isEmpty(relationProjectList)) {
                log.info("当前建设单位未关联任何项目");
                return Pair.of(getFileName(request), Collections.emptyList());
            }
            request.setProjects(relationProjectList);
        }

        List<ProjectDO> projects = projectReportMapper.listEffectProjectByCondition(request);
        return Pair.of(getFileName(request), ProjectConvert.buildProjectVoList(projects));
    }

    /**
     * 获取文件名
     * @param request
     * @return
     */
    private String getFileName(ProjectReportStatisticsRequest request) {
        // 前置校验
        ProjectTempTaskDO taskDO = projectTempTaskMapper.selectDOById(request.getId());
        AssertUtil.assertNotNull(taskDO, "临时提报任务不存在");
        String reportStatus = request.getReportStatus() == 0 ? "未提报" : "已提报";
        String date = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        String fileName = String.format("[%s-%s][%s]项目名单-[%s]", taskDO.getTaskNum(), taskDO.getName(), reportStatus, date);
        return fileName;
    }
}
